package com.socket.nio.nio.sticky.delimiterbased;

import com.socket.nio.nio.constant.NioConstant;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;

/**
 * @author Hexudong
 * @date 2025/5/5
 */
public class DelimiterClient {
  private final String host;

  private final int port;

  public DelimiterClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
              // 创建分隔符ByteBuf
              ByteBuf delimiter = Unpooled.copiedBuffer(NioConstant.DELIMITER, CharsetUtil.UTF_8);

              // 添加固定长度解码器
              ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
              // 将ByteBuf转换为String
              ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
              // 业务处理器
              ch.pipeline().addLast(new DelimiterClientHandler());
            }
          });
      ChannelFuture channelFuture = b.connect(this.host, this.port).sync();

      Channel channel = channelFuture.channel();
      sendDelimitedMessage(channel, "Hello");
      sendDelimitedMessage(channel, "Netty");
      sendDelimitedMessage(channel, "Delimiter");

      channel.closeFuture().sync();
    } finally {
      group.shutdownGracefully();
    }
  }

  /**
   * 发送固定长度的消息
   *
   * @param channel 渠道
   * @param msg 消息
   */
  private void sendDelimitedMessage(Channel channel, String msg) {
    String fullMsg = msg + NioConstant.DELIMITER;
    channel.writeAndFlush(Unpooled.copiedBuffer(fullMsg, CharsetUtil.UTF_8));
  }

  public static void main(String[] args) throws Exception {
    new DelimiterClient("localhost", 8082).run();
  }
}
